extends Node
class_name LevelManager

@export var board_manager: GridMapBoardManager
@export var current_level_index: int = 0

var levels = []

signal level_loaded(level_data: Dictionary)

func _ready():
	if not board_manager:
		board_manager = get_node_or_null("/root/Main/Board")
	
	load_all_level_definitions()
	if board_manager and levels.size() > 0:
		load_level(current_level_index)

func _input(event):
	if event.is_action_pressed("next_level"):
		next_level()
		update_level_label()
	elif event.is_action_pressed("previous_level"):
		previous_level()
		update_level_label()

func update_level_label():
	var label = get_node_or_null("/root/Main/UI/DebugInfo/LevelLabel")
	if label and current_level_index < levels.size():
		var level = levels[current_level_index]
		label.text = "Level: " + level["name"] + "\nPress Q/E to change levels"

func load_all_level_definitions():
	# Define built-in levels
	levels = [
		create_classic_level(),
		create_lanes_level(),
		create_arena_level(),
		create_fortress_level()
	]

func create_classic_level() -> Dictionary:
	return {
		"name": "Classic",
		"description": "Standard auto-chess board",
		"pattern": "default",
		"special_rules": [],
		"max_units": 8
	}

func create_lanes_level() -> Dictionary:
	return {
		"name": "Three Lanes",
		"description": "Battle across three distinct lanes",
		"pattern": "lanes",
		"special_rules": ["lane_locked"],
		"max_units": 9,
		"obstacles": [
			{"x": 7, "z": 0}, {"x": 7, "z": 1}, {"x": 7, "z": 2},
			{"x": 7, "z": 9}, {"x": 7, "z": 10}, {"x": 7, "z": 11},
			{"x": 14, "z": 0}, {"x": 14, "z": 1}, {"x": 14, "z": 2},
			{"x": 14, "z": 9}, {"x": 14, "z": 10}, {"x": 14, "z": 11}
		]
	}

func create_arena_level() -> Dictionary:
	return {
		"name": "Arena",
		"description": "Fight in a enclosed arena with obstacles",
		"pattern": "arena",
		"special_rules": ["no_retreat"],
		"max_units": 7
	}

func create_fortress_level() -> Dictionary:
	var obstacles = []
	# Create fortress walls
	for x in range(5, 16):
		if x != 10:  # Leave gate open
			obstacles.append({"x": x, "z": 5})
			obstacles.append({"x": x, "z": 6})
	
	return {
		"name": "Fortress",
		"description": "Defend or assault the fortress",
		"pattern": "custom",
		"special_rules": ["defender_bonus"],
		"max_units": 10,
		"obstacles": obstacles,
		"tiles": []
	}

func load_level(index: int):
	if index < 0 or index >= levels.size():
		push_error("Invalid level index: " + str(index))
		return
	
	current_level_index = index
	var level_data = levels[index]
	
	if board_manager:
		# Clear and rebuild board based on pattern
		if level_data.has("pattern"):
			match level_data["pattern"]:
				"default":
					board_manager.create_default_board()
				"lanes":
					board_manager.create_pattern("lanes")
				"arena":
					board_manager.create_pattern("arena")
				"custom":
					board_manager.load_level(level_data)
		
		# Add obstacles if specified
		if level_data.has("obstacles"):
			for obstacle in level_data["obstacles"]:
				board_manager.set_tile_type(obstacle.x, obstacle.z, GridMapBoardManager.TileType.OBSTACLE)
	
	emit_signal("level_loaded", level_data)
	print("Level loaded: ", level_data["name"])

func next_level():
	var next_index = (current_level_index + 1) % levels.size()
	load_level(next_index)

func previous_level():
	var prev_index = current_level_index - 1
	if prev_index < 0:
		prev_index = levels.size() - 1
	load_level(prev_index)

func get_current_level() -> Dictionary:
	if current_level_index >= 0 and current_level_index < levels.size():
		return levels[current_level_index]
	return {}

func save_custom_level(level_data: Dictionary, filename: String):
	var file = FileAccess.open("user://levels/" + filename + ".json", FileAccess.WRITE)
	if file:
		file.store_string(JSON.stringify(level_data))
		file.close()
		print("Level saved: ", filename)

func load_custom_level(filename: String) -> Dictionary:
	var file = FileAccess.open("user://levels/" + filename + ".json", FileAccess.READ)
	if file:
		var json_string = file.get_as_text()
		file.close()
		var json = JSON.new()
		var parse_result = json.parse(json_string)
		if parse_result == OK:
			return json.data
	return {}